"""
Lambda函数（简化版）：接收点击事件并写入Kinesis
暂时不使用jsonschema验证
"""
import json
import os
import boto3

# 初始化Kinesis客户端
# LocalStack 自动注入 AWS_ENDPOINT_URL，优先使用它
endpoint_url = os.getenv('AWS_ENDPOINT_URL') or os.getenv('AWS_ENDPOINT')
kinesis_client = boto3.client(
    'kinesis',
    endpoint_url=endpoint_url,
    region_name=os.getenv('AWS_REGION', 'us-east-1')
)


def lambda_handler(event, context):
    """
    Lambda入口函数：接收报文并写入Kinesis
    - 智能裁剪过大字段（visualProximity）
    - 避免超过Kinesis 1MB限制
    """
    try:
        # 获取原始body
        if 'body' in event:
            raw_body = event['body'] if isinstance(event['body'], str) else json.dumps(event['body'])
        else:
            raw_body = json.dumps(event)
        
        # 解析JSON并处理
        try:
            parsed = json.loads(raw_body)
            partition_key = parsed.get('userId', 'unknown_user')
            
            # 智能裁剪：删除超大的 visualProximity 字段
            if 'interactionContext' in parsed and 'visualProximity' in parsed['interactionContext']:
                visual_proximity = parsed['interactionContext']['visualProximity']
                visual_size = len(json.dumps(visual_proximity))
                
                # 如果 visualProximity > 500KB，删除或精简
                if visual_size > 500 * 1024:
                    print(f"🔧 裁剪 visualProximity: {visual_size/1024:.1f} KB")
                    # 保留摘要信息
                    parsed['interactionContext']['visualProximity_summary'] = {
                        'original_size_kb': round(visual_size / 1024, 1),
                        'note': 'Large visualProximity data removed to fit Kinesis limit'
                    }
                    del parsed['interactionContext']['visualProximity']
            
            # 重新序列化
            processed_body = json.dumps(parsed)
            
        except:
            # 如果不是JSON，保持原样
            processed_body = raw_body
            partition_key = 'raw_message'
        
        # 写入Kinesis
        stream_name = os.getenv('KINESIS_STREAM_NAME', 'click-events-stream')
        response = kinesis_client.put_record(
            StreamName=stream_name,
            Data=processed_body,
            PartitionKey=partition_key
        )
        
        return {
            'statusCode': 200,
            'headers': {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*'
            },
            'body': json.dumps({
                'success': True,
                'sequenceNumber': response['SequenceNumber'],
                'shardId': response['ShardId']
            })
        }
        
    except Exception as e:
        print(f"Error: {str(e)}")
        return {
            'statusCode': 500,
            'headers': {'Content-Type': 'application/json'},
            'body': json.dumps({
                'error': 'Internal Server Error',
                'message': str(e)
            })
        }

